package 优先算法.前缀和.除自身以外数组的乘积;

import java.util.Arrays;

/**
 * https://leetcode.cn/problems/product-of-array-except-self/description/
 */
public class Main {
    public static void main(String[] args) {
        Solution so = new Solution();
        int[] arr = {-1,1,0,-3,3};
        int[] rel = so.productExceptSelf(arr);
        System.out.println(Arrays.toString(rel));
    }
}
class Solution {
    public int[] productExceptSelf(int[] nums) {
        //1.构建前缀积和后缀积
        int n = nums.length;
        long[] f = new long[n];
        long[] g = new long[n];
        //初始化越界位置
        f[0]=1;
        g[n-1]=1;
        for(int i = 1;i < n;i++){
            f[i] = f[i-1] * nums[i-1];
        }
        for(int i = n-2;i >= 0;i--){
            g[i] = g[i+1] * nums[i+1];
        }
        //2。使用
        int[] rel = new int[n];
        for(int i = 0;i < n; i++){
            rel[i] =(int) (f[i] * g[i]);

        }
        return rel;
    }
}